package org.finesys.quartz.support;

import lombok.extern.slf4j.Slf4j;
import org.finesys.common.quartz.core.exception.TaskException;
import org.finesys.quartz.entity.SysJob;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * jar包调用实现
 */
@Component
@Slf4j
public class TaskInvokeJarServiceImpl implements TaskInvokeService {

    @Override
    public void invoke(SysJob sysJob) throws TaskException {
        ProcessBuilder processBuilder = new ProcessBuilder();
        File file = new File(sysJob.getExecutePath());
        processBuilder.directory(file.getParentFile());
        List<String> commands = new ArrayList<>();
        commands.add("java");
        commands.add("-jar");
        commands.add(sysJob.getExecutePath());
        if (StringUtils.hasText(sysJob.getMethodParamsValue())) {
            commands.add(sysJob.getMethodParamsValue());
        }
        processBuilder.command(commands);
        try {
            processBuilder.start();
        } catch (IOException e) {
            log.error("定时任务jar反射执行异常,执行任务：{}", sysJob.getExecutePath());
            throw new TaskException("定时任务jar反射执行异常,执行任务：" + sysJob.getExecutePath());
        }

    }
}
